// 方法1：统计总错误次数和总正确次数
function countTotals(values, options) {
  const { successValue, errorValue } = options
  let totalErrors = 0
  let totalCorrects = 0

  values.forEach((value, index) => {
    if (value === errorValue) {
      totalErrors += 1
    } else if (value === successValue) {
      totalCorrects += 1
    } else {
      console.warn(`发现非${successValue}或${errorValue}的值: ${value} 在索引 ${index}`)
    }
  })

  return { totalErrors, totalCorrects }
}

// 方法2：统计连续错误段数和连续正确段数
function countStreaks(values, options) {
  const { successValue, errorValue } = options
  let totalErrorStreaks = 0
  let totalCorrectStreaks = 0
  let lastValue = null

  values.forEach((value, index) => {
    if (value === errorValue) {
      if (lastValue !== errorValue) {
        totalErrorStreaks += 1
      }
    } else if (value === successValue) {
      if (lastValue !== successValue) {
        totalCorrectStreaks += 1
      }
    }
    lastValue = value
  })

  return { totalErrorStreaks, totalCorrectStreaks }
}

// 方法4：确定当前的连续状态和长度
function getCurrentStreak(values, options) {
  const { errorValue, successValue, successName, errorName } = options

  let currentStreakType = null // 当前连续段的类型（错误/正确）
  let currentStreakLength = 0 // 当前连续段的长度
  let currentStreakTypeBoolean = null // 当前连续段的布尔状态（true 表示正确）

  if (values.length === 0) {
    // 空数组直接返回
    return { currentStreakType, currentStreakLength }
  }

  // 获取最后一个有效值的类型
  const lastValue = values[values.length - 1]

  if (lastValue === errorValue) {
    currentStreakType = errorName
    currentStreakTypeBoolean = false
  } else if (lastValue === successValue) {
    currentStreakType = successName
    currentStreakTypeBoolean = true
  } else {
    // 如果最后一个值不是有效值，直接返回默认值
    return { currentStreakType, currentStreakLength }
  }

  // 从后向前遍历，计算当前连续段长度
  for (let i = values.length - 1; i >= 0; i--) {
    if (values[i] === lastValue) {
      currentStreakLength++
    } else {
      break // 遇到不同值时停止
    }
  }

  return { currentStreakType, currentStreakTypeBoolean, currentStreakLength }
}

// 方法5：计算平均值
function computeAverages(totalErrors, totalCorrects, totalErrorStreaks, totalCorrectStreaks) {
  const averageConsecutiveErrors = totalErrorStreaks > 0 ? parseFloat((totalErrors / totalErrorStreaks).toFixed(2)) : 0

  const averageConsecutiveCorrects =
    totalCorrectStreaks > 0 ? parseFloat((totalCorrects / totalCorrectStreaks).toFixed(2)) : 0

  return {
    averageConsecutiveErrors,
    averageConsecutiveCorrects
  }
}

// 方法6：比较当前连续状态与平均值
function compareStreak(
  currentStreakType,
  currentStreakLength,
  averageConsecutiveErrors,
  averageConsecutiveCorrects,
  options
) {
  const { successName, errorName } = options

  let streakComparisonToAverageConsecutiveErrors = null
  let streakComparisonToAverageConsecutiveCorrects = null

  // console.log('currentStreakType', currentStreakType)

  if (currentStreakType === successName) {
    if (averageConsecutiveCorrects > 0) {
      const difference = currentStreakLength - averageConsecutiveCorrects
      const sign = difference > 0 ? '+' : ''
      streakComparisonToAverageConsecutiveCorrects =
        difference !== 0
          ? `${difference > 0 ? '高于' : '低于'}平均正确段长度 (差距: ${sign}${difference.toFixed(2)})`
          : '等于平均正确段长度 (差距: 0.00)'
    } else {
      streakComparisonToAverageConsecutiveCorrects = '无平均正确段长度数据'
    }
  }

  if (currentStreakType === errorName) {
    if (averageConsecutiveErrors > 0) {
      const difference = currentStreakLength - averageConsecutiveErrors
      const sign = difference > 0 ? '+' : ''
      streakComparisonToAverageConsecutiveErrors =
        difference !== 0
          ? `${difference > 0 ? '高于' : '低于'}平均错误段长度 (差距: ${sign}${difference.toFixed(2)})`
          : '等于平均错误段长度 (差距: 0.00)'
    } else {
      streakComparisonToAverageConsecutiveErrors = '无平均错误段长度数据'
    }
  }

  return {
    streakComparisonToAverageConsecutiveErrors,
    streakComparisonToAverageConsecutiveCorrects
  }
}

// 主方法：整合所有计算
function calculateMetrics(values, options) {
  // 方法1：统计总错误次数和总正确次数
  const totals = countTotals(values, options)
  // 方法2：统计连续错误段数和连续正确段数
  const streaks = countStreaks(values, options)
  // 方法4：确定当前的连续状态和长度
  const currentStreak = getCurrentStreak(values, options)
  // 方法5：计算平均值
  const averages = computeAverages(
    totals.totalErrors,
    totals.totalCorrects,
    streaks.totalErrorStreaks,
    streaks.totalCorrectStreaks
  )
  // 方法6：比较当前连续状态与平均值
  const comparisons = compareStreak(
    currentStreak.currentStreakType,
    currentStreak.currentStreakLength,
    averages.averageConsecutiveErrors, // 对比平均错误段长度
    averages.averageConsecutiveCorrects, // 对比平均正确段长度
    options
  )

  // console.log('comparisons', comparisons)

  return {
    ...averages,
    totalErrors: totals.totalErrors,
    totalCorrects: totals.totalCorrects,
    totalErrorStreaks: streaks.totalErrorStreaks,
    totalCorrectStreaks: streaks.totalCorrectStreaks,
    currentStreakType: currentStreak.currentStreakType,
    currentStreakTypeBoolean: currentStreak.currentStreakTypeBoolean,
    currentStreakLength: currentStreak.currentStreakLength,
    streakComparisonToAverageConsecutiveErrors: comparisons.streakComparisonToAverageConsecutiveErrors,
    streakComparisonToAverageConsecutiveCorrects: comparisons.streakComparisonToAverageConsecutiveCorrects
  }
}

export const getMetrics = (values, options) => {
  // console.log('values', values)
  return calculateMetrics(values, options)
}
